package com.uzhie.web.service.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.uzhie.jt808.jt1078.entity.JT_1205;
import com.uzhie.util.ConcurrentCollection;

import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.Message;

/**
 * Created by TangFei on 2018/10/11.
 */
public class MQOriginReceiveService implements MQReceiveService {

    @Override
    public void onMessage(Message message) {
        LOGGER.fatal("收到远程目录消息");
        handlerCatalog(message);
    }

    //处理远程目录回传
    private void handlerCatalog(Message message) {
        try {
            String simNumber = message.getStringProperty(PARAM);
            LOGGER.info(" 收到了远程目录--->");
            Thread thread = ConcurrentCollection.getInstance().getThread(simNumber);
            LOGGER.info("当前收到的ID是 : " + simNumber + "  ~~~  ConcurrentCollection 的线程容器长度为 : " + ConcurrentCollection.getInstance().getThreadSize());
            //如果线程已经被释放,则不进行下面的激活操作
            if (thread == null) {
                LOGGER.error("~~~~~消息ID为 [" + simNumber + "] 的Thread 为 null ~~~~");
                ConcurrentCollection.getInstance().removeResult(simNumber);
                return;
            }
            LOGGER.info("当前线程ID :[" + thread.getId() + "]");
            //获取消息体内容
            BytesMessage bytesMessage = (BytesMessage) message;
            byte[] body = new byte[(int) bytesMessage.getBodyLength()];
            LOGGER.info(" 远程目录消息长度 : [" + bytesMessage.getBodyLength() + "]--->");
            bytesMessage.readBytes(body);
            LOGGER.info("远程目录body消息内容为 : [" + body.toString() + " ]--->");
            JT_1205 order = new JT_1205(body);
            JSONArray arr = (JSONArray) JSON.toJSON(order.getCatalog());
            ConcurrentCollection.getInstance().setResult(simNumber, arr);
            //激活当前线程等待状态
            synchronized (thread) {
                LOGGER.info("线程 [" + thread.getId() + "] 开始激活");
                thread.notifyAll();
                LOGGER.info("线程 [" + thread.getId() + "] 被激活");
                return;
            }
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}
